package com.joeshing.base.search;

import java.util.List;

import javax.annotation.Resource;

import org.hibernate.SessionFactory;
import org.hibernate.search.FullTextQuery;
import org.hibernate.search.FullTextSession;
import org.hibernate.search.Search;
import org.hibernate.search.query.dsl.QueryBuilder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;

import com.joeshing.base.model.InfoPriceDetail_2011;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:applicationContext.xml", "classpath:applicationContext-security.xml" })
@Transactional
public class SearchResultsHibernate {

	@Resource
	private SessionFactory sessionFactory;

	@Test
	public void test() throws Exception {

		// 使用Hibernate Session初始化索引
		FullTextSession fullTextSession = Search.getFullTextSession(sessionFactory.getCurrentSession());
		// fullTextSession.createIndexer().startAndWait();

		// create native Lucene query unsing the query DSL
		// alternatively you can write the Lucene query using the Lucene query
		// parser
		// or the Lucene programmatic API. The Hibernate Search DSL is
		// recommended though
		QueryBuilder qb = fullTextSession.getSearchFactory().buildQueryBuilder().forEntity(InfoPriceDetail_2011.class).get();
		org.apache.lucene.search.Query query = qb.keyword().onFields("name", "standard").matching("钢筋").createQuery();
		 // wrap Lucene query in a org.hibernate.Query
		FullTextQuery fullTextQuery = fullTextSession.createFullTextQuery(query, InfoPriceDetail_2011.class);
		// execute search

		// fullTextQuery.enableFullTextFilter("bestDriver");
		// fullTextQuery.enableFullTextFilter("security").setParameter("level",
		// 2);

		List<InfoPriceDetail_2011> result = fullTextQuery.list();
		long start = System.currentTimeMillis();
		System.out.println("size=" + result.size());
		int i = 0;
		for (InfoPriceDetail_2011 sysLog : result) {
			System.out.println(sysLog.getId());
			// System.out.println(sysLog.getContent());
			System.out.println(sysLog.getName());
			if(i++==20)
				break;
		}
		System.out.println(System.currentTimeMillis()-start);
	}
}
